<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use backend\modules\business\models\BusinessPig;
use common\components\Upload;
use common\models\business\BusinessPerson;
use common\models\business\NewBusinessInspectionData;
use common\models\business\NewBusinessInspectionField;
use Yii;
use common\models\business\NewBusinessInspection;
use backend\modules\business\models\NewBusinessInspectionSearch;
use yii\db\Expression;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * NewBusinessInspectionController implements the CRUD actions for NewBusinessInspection model.
 */
class NewBusinessInspectionController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all NewBusinessInspection models.
     * @return mixed
     */
    public function actionIndex()
    {


        $searchModel = new NewBusinessInspectionSearch();
        $search = Yii::$app->request->queryParams;
        $search['NewBusinessInspectionSearch']['is_del'] = NewBusinessInspectionSearch::ISDEL_NODEL;
        $dataProvider = $searchModel->search($search);


        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single NewBusinessInspection model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        $data = $model->data?$model->data:[];
        $simpledata = [];
        $imgdata = [];
        foreach ($data as $key => $row){
            if($row['fieldtype'] != 'image'){
                $simpledata[] = $row;
            }else if($row['fieldtype'] == 'image'){
                $imgdata[] = $row;
            }
        }

        return $this->render('view', [
            'model' => $model,
            'simpledata' => $simpledata,
            'imgdata' => $imgdata,
        ]);
    }

    /**
     * Creates a new NewBusinessInspection model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new NewBusinessInspection();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing NewBusinessInspection model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            $post = Yii::$app->request->post();

            unset($post['NewBusinessInspection'],$post['_csrf']);
            //更新巡检数据
            $imgfield = (new Query())->select('fieldname,val')->from(NewBusinessInspectionData::tableName())->where('inspectionid=:id and fieldtype="image"',[':id'=>$model->id])->indexBy('fieldname')->all();
            foreach ($imgfield as $key => $row){
                $ff[] = $key;
            }
            unset($imgfield);
            foreach ($post as $key => $row){
                $data['val'] = $row;
                $params = [
                    ':insid' => $model->id,
                    ':name' => $key,
                ];
                Yii::$app->db->createCommand()->update(NewBusinessInspectionData::tableName(),$data,'inspectionid=:insid and fieldname=:name',$params)
                ->execute();
            }

            //更新照片
            foreach ($ff as $key => $row){
                if(false !== $photo = Upload::uploadByName($row)){
                    $data['val'] = $photo;
                    $params = [
                        ':insid' => $model->id,
                        ':name' => $row,
                    ];
                    Yii::$app->db->createCommand()->update(NewBusinessInspectionData::tableName(),$data,'inspectionid=:insid and fieldname=:name',$params)
                        ->execute();
                }
            }
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            $data = $model->data?$model->data:[];
            $simpledata = [];
            $imgdata = [];
            foreach ($data as $key => $row){
                if($row['fieldtype'] != 'image'){
                    $simpledata[] = $row;
                }else if($row['fieldtype'] == 'image'){
                    $imgdata[] = $row;
                }
            }
            return $this->render('update', [
                'model' => $model,
                'simpledata' => $simpledata,
                'imgdata' => $imgdata,
            ]);
        }
    }

    /**
     * Deletes an existing NewBusinessInspection model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
//    public function actionDelete($id)
//    {
//        $this->findModel($id)->delete();
//
//        return $this->redirect(['index']);
//    }
//

    public function actionDelete($id)
    {
        Yii::$app->db->createCommand()->update(NewBusinessInspection::tableName(),['is_del'=>NewBusinessInspection::ISDEL_DEL],'id=:id',[':id'=>$id])
            ->execute();
//        $this->findModel($id)->delete();
        return $this->redirect(['index']);
    }


    /**
     * 回收站
     */
    public function actionRecycle()
    {
        $searchModel = new NewBusinessInspectionSearch();
        $search = Yii::$app->request->queryParams;
        $search['NewBusinessInspectionSearch']['is_del'] = NewBusinessInspection::ISDEL_DEL;
        $dataProvider = $searchModel->search($search);

        return $this->render('recycle', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * @param $id
     * @return string
     * 从回收站恢复
     */
    public function actionRecycleBack($id)
    {
        $res = Yii::$app->db->createCommand()->update(NewBusinessInspection::tableName(),['is_del'=>NewBusinessInspection::ISDEL_NODEL],'id=:id',[':id'=>$id])
            ->execute();

        return $res?$this->dialog('操作成功','success',Url::to(['index'])):$this->dialog('操作失败');
    }






    //批量设置审核
    public function actionSetpass()
    {
        $ids = Yii::$app->request->post('ids');
        if(!empty($ids)){
            $idstr = implode(',',$ids);
            Yii::$app->db->createCommand('update '.NewBusinessInspection::tableName().' set status=:status where id in('.$idstr.')')
                ->bindValues([':status'=>NewBusinessInspection::STATUS_PASSED])
                ->execute();
            return \GuzzleHttp\json_encode(['msg'=>'操作成功','status'=>0]);
        }

        return \GuzzleHttp\json_encode(['msg'=>'请选择对应的仔猪','status'=>1]);


    }


    /**
     * @return string
     * 批量删除巡检记录
     */
    public function actionMutiDelete()
    {
        $ids = Yii::$app->request->post('ids');
        if(!empty($ids)){
            $idstr = implode(',',$ids);
            Yii::$app->db->createCommand('update '.NewBusinessInspection::tableName().' set is_del=:is_del where id in('.$idstr.')')
                ->bindValues([':is_del'=>NewBusinessInspection::ISDEL_DEL])
                ->execute();
            return \GuzzleHttp\json_encode(['msg'=>'操作成功','status'=>0]);
        }

        return \GuzzleHttp\json_encode(['msg'=>'请选择对应的仔猪','status'=>1]);

    }

    /**
     * Finds the NewBusinessInspection model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return NewBusinessInspection the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = NewBusinessInspection::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    /**
     *
     * 巡检日历
     */
    public function actionShowDate($pigid)
    {
        $this->layout = false;
        return $this->render('_dateshow',[
            'pigid' => $pigid,
        ]);
    }


    /**
     *
     * 获取日期巡检记录的数据
     */
    public function actionGetShowdata()
    {
        $start = Yii::$app->request->get('start');
        $end = Yii::$app->request->get('end');
        $pigid = Yii::$app->request->get('pigid');
        $createtime = new Expression('FROM_UNIXTIME(createtime,"%Y-%m-%d") as start');
        $ins = (new Query())->select([$createtime,'ins.status','ins.id'])
            ->from(['ins'=>NewBusinessInspection::tableName()])
            ->leftJoin(['pig'=> BusinessPig::tableName()],'pig.id=ins.pigid')
            ->where('pigid=:pigid and createtime>=:start and createtime <= :end and is_del!=:is_del',[
                ':pigid'=>intval($pigid),
                ':start'=>intval($start),
                ':end' => intval($end),
                ':is_del' => NewBusinessInspection::ISDEL_DEL
            ])
            ->all();
        foreach ($ins as $key => $row){
            if($row['status'] == NewBusinessInspection::STATUS_NOLOOK){
                $ins[$key]['backgroundColor'] = '#777';
            }else if($row['status'] == NewBusinessInspection::STATUS_UNPASSED){
                $ins[$key]['backgroundColor'] = 'red';
            }else if($row['status'] == NewBusinessInspection::STATUS_PASSED){
                $ins[$key]['backgroundColor'] = 'green';
            }
            $ins[$key]['color'] = '#fff';
            $ins[$key]['url'] = Url::to(['/business/new-business-inspection/view','id'=>$row['id']]);

            $ins[$key]['title'] = NewBusinessInspection::$statues[$row['status']];
        }

        return \GuzzleHttp\json_encode($ins);
    }


}
